<template>
	<view class="order-form" :style="{height: this.appHeight+'rpx'}">
		<u-toast ref="uToast"></u-toast>
		<u-toast ref="uToast2"></u-toast>
		<u--form
				labelPosition="left"
				:model="orderForm"
				:rules="rules"
				ref="uForm"
				>
					<u-form-item
							class="item-box"
							label-width="90px"
							label="订单编号"
							prop="orderCode"
							borderBottom
							ref="item1"
					>	
						<span class="asterisk">*</span>
						<u--input
								v-model="orderForm.orderCode"
								 border="surround"
								 disabled="true"
						></u--input>
					</u-form-item>
					<u-picker :show="orderStatusShow" :columns="orderStatus" @cancel="orderStatusShow=false" @confirm="orderStatusConfirm"></u-picker>
					<u-form-item
							class="item-box"
							label-width="90px"
							label="订单状态"
							prop="orderStatus"
							borderBottom
							ref="item1"
					>
						<span class="asterisk">*</span>
						<u--input
								v-model="orderForm.orderStatus"
								 border="surround"
								 disabled="true"
						>
						</u--input>
					</u-form-item>
<!-- 					<u-picker :show="expressShow" :columns="expressDelivery" @cancel="expressClose" @confirm="expressConfirm"></u-picker>
					<u-form-item
							class="item-box"
							label-width="90px"
							label="发货快递"
							prop="expressDelivery"
							borderBottom
							ref="item1"
							style="position: relative;"
					>
						<span class="asterisk">*</span>
						<view v-show="sendExpressShow" style="position:absolute;
						top:48px;left: 90px;background-color: white;z-index: 9;padding-left: 20px;">
							<p v-for="(item,index) in sendExpress" :key="index" style="cursor: pointer;margin-top:5px;" @click="expressText(index)">{{item.logisticsName}}</p>
						</view>
						<u--input
								v-model="orderForm.expressDelivery"
								 border="surround"
								 @input="inputExpress"
						>	
							<template slot="suffix">
								<u-button
									@click="expressShow=true"
									:hairline="false"
									size="mini"
									border="nonde"
									icon="arrow-down"
								></u-button>
							</template>
						</u--input>
					</u-form-item>
							
					<u-form-item
							class="item-box"
							label-width="90px"
							label="快递单号"
							prop="expressNO"
							borderBottom
							ref="item1"
					>
						<span class="asterisk">*</span>
						<u--input
								v-model="orderForm.expressNO"
								border="surround"
						></u--input>
					</u-form-item> -->
					<u-form-item
							class="item-box"
							label-width="90px"
							label="门店省市区"
							prop="position"
							borderBottom
							ref="item1"
					>
						<span class="asterisk">*</span>
						<template style="flex: 1;width: 0;">
							<area-select v-if="isArea" type="all" :level="2" v-model="address1" :data="pcaa"></area-select>
						</template>
		
					</u-form-item>
					<u-picker :show="agentShow" :columns="agent" @cancel="agentShow=false" @confirm="agentConfirm"></u-picker>
					<u-form-item
							class="item-box"
							label-width="90px"
							label="代理商"
							prop="agent"
							borderBottom
							ref="item1"
							style="position: relative;"
					>
						
						<span class="asterisk">*</span>
						<view v-show="agentLikeShow" style="position:absolute;
						top:48px;left: 90px;background-color: white;z-index: 9;padding-left: 20px;">
							<p v-for="(item,index) in agentLike" :key="index" style="cursor: pointer;margin-top:5px;" @click="agentText(index)">{{item.name}}</p>
						</view>
						<u--input
								v-model="orderForm.agent"
								border="surround"
								@input="agentInput"
						>
							<template slot="suffix">
								<u-button
									@click="agentShow=true"
									:hairline="false"
									size="mini"
									border="nonde"
									icon="arrow-down"
								></u-button>
							</template>
						</u--input>
					</u-form-item>
					<u-form-item
							class="item-box"
							label-width="90px"
							label="门店名称"
							prop="name"
							borderBottom
							ref="item1"
					>
						<span class="asterisk">*</span>
						<u--input
								v-model="orderForm.name"
								border="surround"
						></u--input>
					</u-form-item>
					<u-form-item
							class="item-box"
							label-width="90px"
							label="门店联系人"
							prop="contacts"
							borderBottom
							ref="item1"
					>
						<span class="asterisk">*</span>
						<u--input
								v-model="orderForm.contacts"
								border="surround"
						></u--input>
					</u-form-item>
					<u-form-item
							class="item-box"
							label-width="90px"
							label="门店电话"
							prop="phone"
							borderBottom
							ref="item1"
							type="number"
					>
						<span class="asterisk">*</span>
						<u--input
								v-model="orderForm.phone"
								border="surround"
						></u--input>
					</u-form-item>
					<!-- <u-form-item
							class="item-box"
							label-width="90px"
							label="内机SN码"
							prop="code"
							borderBottom
							ref="item1"
					>
						<u--input
								style="margin-left: 14px;"
								v-model="orderForm.code"
								border="surround"
						></u--input>
					</u-form-item> -->
					<!-- <view style="display: flex;justify-content: space-between;">
						<view class="container">
							<view>SN码图片 </view>
							<u-upload
							    :fileList="fileList1"
							    @afterRead="afterRead"
							    @delete="deletePic"
							    name="1"
							    multiple
							    :maxCount="5"
								deletable="true"
							  ></u-upload>
						</view>
						<view class="container">
							<view>其他图片 </view>
							<u-upload
							    :fileList="fileList2"
							    @afterRead="afterRead2"
							    @delete="deletePic2"
							    name="1"
							    multiple
							    :maxCount="5"
								deletable="true"
							  ></u-upload>
						</view>
					</view> -->
	</u--form>
	
	<view style="display: flex;justify-content: space-between;margin-top: 20px;">
		<u-button type="success" style="width: 100px;" :disabled="orderForm.orderStatus !== '已发货'" @click="orderReturn">
			退货
		</u-button>
		<u-button type="primary" style="width: 100px;" :disabled="orderForm.orderStatus !== '待发货'" @click="sendOrder">
			提交
		</u-button>
	</view>
	</view>
</template>

<script>
	import { regionData ,CodeToText} from 'element-china-area-data'
	import { getNoStateOrder,sendOrder,findAgent,orderReturn} from '../../../api/order';
	import { pca, pcaa } from 'area-data';
	// import AreaSelect from '../../area-select/index.vue'
export default {
	// components: {
	// 	AreaSelect
	// },
	data() {
		return {
			isInput:true,
			address:"",
			fileList1: [],
			fileList2:[],
			isArea:true,
			options: regionData,
			isshow:false,
			areaArr:[],
			address1:[], // 接收数据的对象
			pca: pca,
			pcaa: pcaa,
			orderForm: {
				id:"",
				orderCode:"",
				orderStatus:"",
				expressDelivery:"",
				expressNO:"",
				position:"",
				agent:"",
				name:"",
				contacts:"",
				phone:"",
				code:""
			},
			expressShow: false,
			expressDelivery: [
				[]
			],
			positionShow:false,
			agentShow:false,
			agentTemp:"",
			agent:[
				[]
			],
			orderStatusShow:false,
			orderStatus:[
				['未付款','待审核','待发货','已发货','交易成功','交易关闭']
			],
			imageSNList: [] ,// 存储已上传图片的地址
			imageOtherList:[],
			agentList:[],
			sendForm:{
				expressNO:"",
				agentId:"",
				id:"",
				state:"",
				city:"",
				district:"",
				address:"",
				name:"",
				phone:"",
				isDummy:0,
				logisticsCode:"",
				tenantId:5431,
				logisticsId:"",
				logisticsName:"",
				tid:"",
				shopId:"",
				shopType:"",
				shopName:""
			},
			expressList:[],
			sendExpressShow:false,
			expressTemp:"",
			sendExpress:[],
			rules: {
				'orderCode': {
					type: 'string',
					required: true,
					message: '订单号不能为空',
					trigger: ['blur', 'change']
				},
				'orderStatus': {
					type: 'string',
					required: true,
					message: '订单状态不能为空',
					trigger: ['blur', 'change']
				},
				'expressDelivery': {
					type: 'string',
					required: true,
					message: '快递公司不能为空',
					trigger: ['blur', 'change']
				},
				'expressNO': {
					type: 'string',
					required: true,
					message: '快递单号不能为空',
					trigger: ['blur', 'change']
				},
				'agent': {
					type: 'string',
					required: true,
					message: '代理商不能为空',
					trigger: ['blur', 'change']
				},
				'name': {
					type: 'string',
					required: true,
					message: '门店地址不能为空',
					trigger: ['blur', 'change']
				},
				'contacts': {
					type: 'string',
					required: true,
					message: '门店联系人不能为空',
					trigger: ['blur', 'change']
				},
				'phone': {
					type: 'number',
					required: true,
					message: '门店联系人电话不能为空',
					trigger: ['blur', 'change']
				},
			},
			agentLike:[],
			agentLikeShow:true,
			appHeight:""
		};
	},
	watch:{
		address1(newName,oldName){
			const province1 = Object.keys(newName[0])[0]
			const state = pcaa[86][province1]
			findAgent({province:state,tenantId:5431}).then(res => {
				this.agentList = res;
				const names = res.map(item => item.name);
				this.agent=[[...names]]
			})
			
		}
	},
	onReady() {
	 this.$refs.eForm.setRules(this.rules)
	},
	methods: {
		// 删除图片
		      deletePic2(event) {
		        this.fileList2.splice(event.index, 1);
		      },
			  deletePic(event) {
			    this.fileList1.splice(event.index, 1);
			  },
		      // 新增图片
		      async afterRead(event) {
		        // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		        let lists = [].concat(event.file);
		        let fileListLen = this.fileList1.length;
		        lists.map((item) => {
		          this.fileList1.push({
		            ...item,
		          });
		        });
		        for (let i = 0; i < lists.length; i++) {
		          const result = await this.uploadFilePromise(lists[i].url);
		          let item = this.fileList1[fileListLen];
		          this.fileList1.splice(
		            fileListLen,
		            1,
		            Object.assign(item, {
		              status: "success",
		              message: "",
		              url: result,
		            })
		          );
		          fileListLen++;
		        }
		      },
			  // 新增图片
			  async afterRead2(event) {
			    // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			    let lists = [].concat(event.file);
			    let fileListLen = this.fileList2.length;
			    lists.map((item) => {
			      this.fileList2.push({
			        ...item,
			      });
			    });
			    for (let i = 0; i < lists.length; i++) {
			      const result = await this.uploadFilePromise(lists[i].url);
			      let item = this.fileList2[fileListLen];
			      this.fileList2.splice(
			        fileListLen,
			        1,
			        Object.assign(item, {
			          status: "success",
			          message: "",
			          url: result,
			        })
			      );
			      fileListLen++;
			    }
			  },
		      uploadFilePromise(url) {
		        return new Promise((resolve, reject) => {
		          let a = uni.uploadFile({
		            url: "http://192.168.2.21:7001/upload", // 仅为示例，非真实的接口地址
		            filePath: url,
		            name: "file",
		            formData: {
		              user: "test",
		            },
		            success: (res) => {
		              setTimeout(() => {
		                resolve(res.data.data);
		              }, 1000);
		            },
		          });
		        });
		      },
		chooseImage() {
		      uni.chooseImage({
		        count: 5, // 一次最多可以选择 9 张图片，可根据需求调整
		        sizeType: ['original', 'compressed'], // 可以选择原图或压缩图
		        sourceType: ['album', 'camera'], // 图片来源可以是相册或相机
		        success: (res) => {
		          // 将选择的图片临时路径添加到 imageList 数组中
		          this.imageSNList = this.imageSNList.concat(res.tempFilePaths);
		        },
		        fail: (err) => {
		        }
		      });
		    },
		showToast(params) {
			this.$refs.uToast.show({
			  ...params
			});
		},
		orderReturn(){
			this.showToast(
			{
				loading:"true",
				type: "loading",
				position:"top",
				message:"正在加载",
				duration:30000,
				complete:() => {
					this.$refs.uToast2.show({
					  message:"服务器繁忙，请重试",
					  type: "warning",
					  position:"top"
					});
				}
			}
			)
			orderReturn({tenantId:5431,id:this.orderForm.id,isReturn:1}).then(res=>{
				if(res){
					this.showToast(
					{
						message:"退货标记成功",
						type: "success",
						position:"top"
					}
					);
				}else{
					this.showToast(
					{
						message:"退货标记失败",
						type: "error",
						position:"top"
					}
					);
				}
			})
		},
		// 给代理商赋值
		agentText(index){
			this.isInput=false
			this.orderForm.agent = this.agentLike[index].name
			this.agentLikeShow=false
			this.agentTemp = this.orderForm.agent
		},
		// 代理商模糊查询
		agentInput(e){
			this.isInput=true
			if(this.agentTemp === this.orderForm.agent){
				return;
			}
			this.agentLike=[]
			this.agentLikeShow=true
			for (var item =0;item < this.agentList.length;item++) {
				if((this.agentList[item].name).includes(e)){
					this.agentLikeShow=false
					this.agentLike.push(this.agentList[item])
					var t = setTimeout(() => {this.agentLikeShow = true},0);
				}
			}
		},
		dataFormat(){
			for (var item =0;item < this.agentList.length;item++) {
				if(this.agentList[item].name === this.orderForm.agent){
					this.sendForm.agentId  = this.agentList[item].id
				}
			}
			for (var item =0;item < this.expressList.length;item++) {
				if(this.expressList[item].logisticsName === this.orderForm.expressDelivery){
					this.sendForm.logisticsCode  = this.expressList[item].logisticsCode
					this.sendForm.logisticsName = this.expressList[item].logisticsName
					this.sendForm.logisticsId = this.expressList[item].id
				}
			}
			this.sendForm.tid = this.orderForm.orderCode
			this.sendForm.expressNO = this.orderForm.expressNO
			this.sendForm.id = this.orderForm.id
			this.sendForm.name = this.orderForm.contacts
			this.sendForm.phone = this.orderForm.phone
			this.sendForm.address = this.orderForm.name
			this.sendForm.state = pcaa[86][Object.keys(this.address1[0])[0]]
			this.sendForm.city = pcaa[Object.keys(this.address1[0])[0]][Object.keys(this.address1[1])[0]]
			this.sendForm.district = pcaa[Object.keys(this.address1[1])[0]][Object.keys(this.address1[2])[0]]
		},
		sendOrder(){
			this.$refs.uForm
			.validate()
				.then(res => {	
				this.dataFormat();
				if(!this.address1){
					return ;
				}
				if(this.isInput){
					this.showToast(
					{
						type: "error",
						position:"top",
						message:"代理商需输入后选择，不能全手工输入",
						duration:3000
					})
					return;
				}
				this.showToast(
				{
					loading:"true",
					type: "loading",
					position:"top",
					message:"正在加载",
					duration:30000,
					complete:()=>{
						this.$refs.uToast2.show({
						  message:"服务器繁忙，请重试",
						  type: "warning",
						  position:"top"
						});
					}
				}
				)
				sendOrder(this.sendForm).then(res=>{
					if(res.success){
						this.showToast(
						{
							type: "success",
							position:"top",
							message:"提交成功",
						})
					}else{
						this.showToast(
						{
							type: "error",
							position:"top",
							message:"提交失败："+(res.result).split('FAQ')[0].trim(),
							duration:3000,
						})
					}
				})
			  }).catch(errors => {
					uni.$u.toast('带星号字段未全部填写')
				  })
		},
		sexSelect(e) {
			this.model1.userInfo.sex = e.name
			this.$refs.uForm.validateField('userInfo.sex')
		},
		expressClose(){
			this.expressShow=false
		},
		expressConfirm(e){
			this.orderForm.expressDelivery=e.value[0];
			this.expressClose();
		},
		changeHandler(e) {
			const {
				columnIndex,
				value,
				values, // values为当前变化列的数组内容
				index,
				// 微信小程序无法将picker实例传出来，只能通过ref操作
				picker = this.$refs.uPicker
			} = e
			// 当第一列值发生变化时，变化第二列(后一列)对应的选项
			if (columnIndex === 0) {
				// picker为选择器this实例，变化第二列对应的选项
				picker.setColumnValues(1, this.columnData[index])
			}
		},
		// 给代理商赋值
		expressText(index){
			this.orderForm.expressDelivery = this.sendExpress[index].logisticsName
			this.sendExpressShow=false
			this.expressTemp = this.orderForm.expressDelivery
		},
		// 快递模糊查询
		inputExpress(e){
			if(this.expressTemp === this.orderForm.expressDelivery){
				return;
			}
			this.sendExpress=[]
			for (var item =0;item < this.expressList.length;item++) {
				if((this.expressList[item].logisticsName).includes(e)){
					this.sendExpressShow=true
					this.sendExpress.push(this.expressList[item])
					var t = setTimeout(() => {this.sendExpressShow = true},0);
				}
			}
		},
		// 回调参数为包含columnIndex、value、values
		confirm(e) {
			this.orderForm.position=e.value[0]+" "+e.value[1]
			this.positionShow = false
		},
		agentConfirm(e){
			this.isInput=false
			this.orderForm.agent=e.value[0];
			this.agentShow=false
		},
		orderStatusConfirm(e){
			this.orderForm.orderStatus=e.value[0];
			this.orderStatusShow=false;
		},
		// 预览图片的方法
		previewImage(index) {
		  uni.previewImage({
			current: this.imageSNList[index], // 当前预览的图片
			urls: this.imageSNList // 预览的图片列表
		  });
		},
		// 预览图片的方法
		previewImageOther(index) {
		  uni.previewImage({
			current: this.imageOtherList[index], // 当前预览的图片
			urls: this.imageOtherList // 预览的图片列表
		  });
		}
	},
	onLoad: function (option) {
		uni.getSystemInfo({
			success: res => {
				console.log('手机可用高度:' + res.windowHeight * 2 + 'rpx');
				
				this.appHeight = res.windowHeight * 2-40;
			}
		});
		// 初始化页面数据
		const item = option.tid;
		getNoStateOrder(item).then(res => {
			this.sendForm.shopId=res[0].shopId
			this.sendForm.shopType = res[0].shopType
			this.sendForm.shopName = res[0].shopName
			this.orderForm={
				id:res[0].id,
				orderCode:res[0].tId,
				orderStatus:res[0].orderState===99?'交易关闭':this.orderStatus[0][res[0].orderState-1],
				expressDelivery:res[0].logisticsName,
				expressNO:res[0].expressNo,
				position:"",
				agent:"",
				name:"",
				contacts:"",
				phone:""
			}
			this.expressTemp=res[0].logisticsName
			if(res[0].agent){
				this.orderForm.agent=res[0].agent.name	
				this.agentTemp = res[0].agent.name
			}
			if(res[0].shopAdd){
				this.orderForm.name=res[0].shopAdd.senderAddress
				this.orderForm.contacts=res[0].shopAdd.senderName
				this.orderForm.phone=res[0].shopAdd.senderMobile | res[0].shopAdd.senderPhone
				this.isArea = false
				this.address1[0]=res[0].shopAdd.senderState
				this.address1[1]=res[0].shopAdd.senderCity
				this.address1[2]=res[0].shopAdd.senderDistrict
				var t = setTimeout(() => {this.isArea = true},0);
			}
			this.imageSNList.push(res[0].picPath)
			this.expressList= res[0].expressList;
			this.expressDelivery=[[...this.expressList.map(item => item.logisticsName)]]
		})
	},
	positionListen(e){
	}
}
</script>

<style lang="scss">
.asterisk{
	font-size: 16px;
	color: red;
	margin-right: 5px;
}
::v-deep .area-select-wrap .area-select{
	margin:0px;
}
::v-deep .area-select.medium {
	width:auto;
}
.order-form{
	padding: 10px 20px 0px 20px;
	box-sizing: border-box;
}
.item-box{
	font-weight: bold;
	margin-bottom: 40rpx;
}
.container {
  padding: 20px;
  text-align: center;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.image-item {
  width: 200rpx;
  height: 200rpx;
}

.image-item image {
  width: 100%;
  height: 100%;
}
</style>
